package kr.saeildamil.androidstudy.ch17;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class SaveState extends Activity {
	
	private MyView mv;
	int x;
	int y;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(savedInstanceState==null){
			x = 50;
		}else{
			x = savedInstanceState.getInt("x");
		}
		SharedPreferences pref = getSharedPreferences("SaveState", MODE_PRIVATE);
		y = pref.getInt("y", 50);
		mv = new MyView(this);
		mv.setFocusable(true);
		mv.setFocusableInTouchMode(true);
		setContentView(mv);
	}
	
/*	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if(savedInstanceState==null){
			x = 50;
			mv.invalidate();
		}else{
			x = savedInstanceState.getInt("x");
			mv.invalidate();
		}
	}*/
	
	@Override
	protected void onPause() {
		super.onPause();
		SharedPreferences pref = getSharedPreferences("SaveState", MODE_PRIVATE);
		SharedPreferences.Editor edit = pref.edit();
		edit.putInt("y", y);
		edit.commit();				// commit 을 해 주어야 저장이 됨;
		
	}
	
	protected void onSaveInstanceState(Bundle outState) {
		 super.onSaveInstanceState(outState);
		 outState.putInt("x", x);
	}

	protected class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
			
			protected void onDraw(Canvas canvas){
				super.onDraw(canvas);
				Paint p = new Paint();
				p.setColor(Color.GREEN);
				canvas.drawCircle(x, y, 16, p);
			}
			
			public boolean onTouchEvent(MotionEvent event){
				super.onTouchEvent(event);
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					x += 15;
					y += 15;
					invalidate();
					return true;
				}		
				return false;
		}
	}	
}
